package problem322;

//322.零钱兑换
//https://leetcode.cn/problems/coin-change/description/

// class Solution {
//     public int coinChange(int[] coins, int m) {
//         int n = coins.length;
//         int[][] dp = new int[n+1][m+1];
//         for(int j = 1; j<=m; j++) {
//             dp[0][j] = 0x3f3f3f3f;
//         }
//         for(int i = 1; i<=n; i++) {
//             for(int j = 0; j<=m; j++) {
//                 dp[i][j] = dp[i-1][j];
//                 if(j-coins[i-1] >= 0 ) dp[i][j] = Math.min(dp[i][j], dp[i][j-coins[i-1]] + 1);
//             }
//         }
//         return dp[n][m]==0x3f3f3f3f?-1:dp[n][m];
//     }
// }

/*
dp[i][j]:从前i种面值的硬币中选, 金额不超过 j, 所需的最少硬币数, dp[i][j] = -1 表示无法组成

dp[i][j] = min(dp[i-1][j], dp[i-1][j-coins[i]] + 1, dp[i-1][j-2*coins[i]] + 2, ..., dp[i-1][j-k*coins[i]] + k);
dp[i][j-coins[i]] = min(dp[i-1][j-coins[i]], dp[i-1][j-2*coins[i]] + 1, ... , dp[i-1][j-k*coins[i]] + k-1);
dp[i][j] = min(dp[i-1][j], dp[i][j-coins[i]] + 1);
*/

class Solution {
    public int coinChange(int[] coins, int m) {
        int n = coins.length;
        int[] dp = new int[m+1];
        for(int j = 1; j<=m; j++) {
            dp[j] = 0x3f3f3f3f;
        }
        for(int i = 1; i<=n; i++) {
            for(int j = coins[i-1]; j<=m; j++) {
                dp[j] = Math.min(dp[j], dp[j-coins[i-1]] + 1);
            }
        }
        return dp[m]==0x3f3f3f3f?-1:dp[m];
    }
}